<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">欢迎登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container"><svg-icon icon-class="user" /></span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container"><svg-icon icon-class="password" /></span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
        />
        <span class="show-pwd" @click="showPwd"><svg-icon
          :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
        /></span>
      </el-form-item>
      <!-- 手机验证码 -->
      <el-form-item prop="code">
        <div style="display: flex;">
          <el-input
            v-model="loginForm.code"
            style="width: 75%;"
            type="text"
            suffix-icon="el-icon-lock"
            placeholder="验证码"
          />
          <el-button type="primary" @click="getCode">{{ valiBtn }}</el-button>
        </div>
      </el-form-item>
      <p v-if="charLpPhone" style="font-size: 14px;">{{ charLpPhone }}</p>
      <!-- /** 绑定手机号 */ -->
      <el-form-item v-if="isPhone" prop="adminUserMobile">
        <div style="display: flex;">
          <el-input
            v-model="loginForm.adminUserMobile"
            style="width: 75%;"
            type="text"
            suffix-icon="el-icon-phone-outline"
            placeholder="请输入手机号"
          />
          <el-button type="primary" @click="setPhone">点击开始绑定</el-button>
        </div>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-top:30px;"
        @click.native.prevent="handleLogin"
      >登录</el-button>

      <!-- <div class="tips">
        <span style="margin-right:20px;">username: admin</span>
        <span>password: any</span>
      </div> -->
    </el-form>
  </div>
</template>

<script>
import { getLoginCode, binding } from '@/api/user/user'
import Fingerprint2 from 'fingerprintjs2'

export default {
  name: 'Login',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const validatePhoneNumber = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('手机号不能为空'))
      }
      // 使用正则表达式进行验证手机号码
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'))
      }
      // 自定义校验规则 需要调用callback()函数！
      callback()
    }
    return {
      // 接收手机号
      charLpPhone: '',
      loginForm: {
        username: '',
        password: '',
        code: '',
        adminUserMobile: undefined,
        fingerprint: '',
        longitudeAndLatitude: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validatePhoneNumber }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        code: [{ required: true, message: '请填写短信验证码', trigger: 'blur' }],
        adminUserMobile: [{ required: true, trigger: 'blur', validator: validatePhone }]
      },
      identifyCodes: '1234567890',
      identifyCode: '',
      loading: false,
      isPhone: false,
      passwordType: 'password',
      redirect: undefined,
      valiBtn: '获取验证码',
      disabled: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    this.identifyCode = ''
    this.getfingerprint()
    this.enterLogin()
    this.pos()
  },
  methods: {
    pos() {
      const geolocation = new BMap.Geolocation()
      var _this = this
      geolocation.getCurrentPosition(function getinfo(position) {
        const { longitude, latitude } = position
        const pos = _this.qqMapTransBMap(longitude, latitude)
        console.log('pos: ', pos)
        _this.loginForm.longitudeAndLatitude = `${pos.longitude},${pos.latitude}`
        console.log(' _this.loginForm: ', _this.loginForm)
      }, function(e) {
        _this.LocationPCity = '定位失败'
      }, { provider: 'baidu' })
    },
    // 将腾讯/高德地图经纬度转换为百度地图经纬度
    qqMapTransBMap(lng, lat) {
      const x_pi = 3.14159265358979324 * 3000.0 / 180.0
      const x = lng
      const y = lat
      const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi)
      const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi)
      const lngs = z * Math.cos(theta) + 0.0065
      const lats = z * Math.sin(theta) + 0.006

      return {
        longitude: lngs,
        latitude: lats
      }
    },
    enterLogin() {
      document.onkeydown = (e) => {
        e = window.event || e
        if (this.$route.path == '/login' && (e.code == 'Enter' || e.code == 'enter')) {
          // 调用登录事件方法
          this.handleLogin()
        }
      }
    },
    // 获取浏览器指纹
    getfingerprint() {
      Fingerprint2.get(components => {
        const values = components.map((component, index) => {
          if (index === 0) {
            return component.value.replace(/\bNetType\/\w+\b/, '')
          }
          return component.value
        })
        // 生成最终id murmur
        const murmur = Fingerprint2.x64hash128(values.join(''), 31)
        this.loginForm.fingerprint = murmur
      })
    },
    //  倒计时60s
    // 获取验证码
    // 获取验证码 并只验证手机号 是否正确
    getCode() {
      if (this.disabled) return
      this.$refs.loginForm.validateField('username', err => {
        if (!err) {
          this.$refs.loginForm.validateField('password', err => {
            if (!err) {
              this.charLpPhone = ''
              getLoginCode({ mobile: this.loginForm.username, password: this.loginForm.password }).then(res => {
                if (res.data.success) {
                  this.tackBtn() // 验证码倒数60秒
                  this.$message.success('验证码发送成功')
                  this.charLpPhone = `已向 ${res.data.msg} 手机发送验证码,请注意查看！`
                } else {
                  if (res.data.msg == '请绑定手机号;') this.isPhone = true
                  this.$message.error(res.data.msg)
                }
              })
            }
          })
        }
      })
    },
    tackBtn() {
      // 验证码倒数60秒
      let time = 60
      const timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer)
          this.valiBtn = '获取验证码'
          this.disabled = false
        } else {
          this.disabled = true
          this.valiBtn = time + '秒后重试'
          time--
        }
      }, 1000)
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 绑定手机号
    setPhone() {
      this.$refs.loginForm.validateField('adminUserMobile', err => {
        if (!err) {
          this.$refs.loginForm.validateField('username', err => {
            if (!err) {
              binding({
                mobile: this.loginForm.username,
                adminUserMobile: this.loginForm.adminUserMobile
              }).then(res => {
                this.$message[res.data.success ? 'success' : 'error'](res.data.msg)
                if (res.data.success) {
                  this.loginForm.adminUserMobile = undefined
                  this.isPhone = false
                }
              })
            }
          })
        }
      })
    },
    // 开始登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          console.log('this.loginForm: ', this.loginForm)
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch(err => {
              this.loading = false
              this.$message.error(err)
            })
        } else {
          console.log(12222)
          this.$log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
$bg: #3b425d;
$light_gray: #fff;
$cursor: #14162e;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 50px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #14162e;
      height: 50px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #f6f5fa inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #f8f7fb;
    border-radius: 5px;
    color: #14162e;
  }

  .el-button--primary {
    color: #fff;
    background-color: $bg;
    border-color: $bg;
  }
}
</style>

<style lang="scss" scoped>
$bg: #3b425d;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background: url('./img/login_bg.jpg') no-repeat;
  background-size: 100% 100%;
  background-position: center;
  // background-color: $bg;
  overflow: hidden;

  .login-form {
    width: 380px;
    max-width: 100%;
    position: absolute;
    top: 30%;
    right: 20%;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .login-code {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;

    .s-canvas {
      height: 50px;
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    ::v-deep canvas {
      height: 50px;
      width: 100px;
    }

    @media only screen and (max-width: 1080px) {
      ::v-deep canvas {
        width: 50px;
        height: 30px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 20px;
      color: #545454;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}</style>
